﻿@{
    Style.Require("jQueryUI_Orchard");
    Style.Require("NineSeas.Common");
    Style.Require("NineSeas.Reader");
    Style.Require("NineSeas.Authoring");
    Style.Require("NineSeas.Authoring.Book.Edit");
    Style.Require("Apprise");

    Script.Require("jQuery").AtHead();
    Script.Require("jQueryUI");
    Script.Require("NineSeas.Common");
    Script.Require("NineSeas.Authoring.Book.Edit");
    Script.Require("NineSeas.MediaUploadButton");
    Script.Require("NineSeas.CommandBar");
    Script.Require("FriendUrl");
    Script.Require("TinyMce");
    Script.Require("TagsAutocomplete");
    Script.Require("Apprise");

    var from = Request.QueryString["from"];
    var fileName = String.IsNullOrEmpty(Model.Book.FileUrl) ? "" : Model.Book.FileUrl;

    if (fileName.IndexOf('/') >= 0)
    {
        fileName = fileName.Substring(fileName.LastIndexOf('/') + 1);
    }
}
<div id="nineseas">
    <div id="nineseas-reader-header">
        <div class="header-bullet"></div>
        @{ if (!Model.IsNew)
         {
            <h1>@T("Edit book information")</h1>
         }
         else
         {
            <h1>@T("Create new book")</h1>
         }
        }
    </div>
    <div id="nineseas-reader-content">
        <div id="edit-area" style="width: 600px; margin: 0 auto;">
            <div class="authoring-edit-image authoring-book-image" id="imageArea">
                <img src="@Model.ImageUrl" alt="@Model.Book.Name" />
                @T("Click to change")
            </div>
            <div class="nineseas-field-label">@T("Name") @Display(New.Controls_HelpPopup(Message: T("The name of the book")))</div>
            <div class="nineseas-field-input">
                <input type="text" id="txtName" name="Name" value="@Model.Book.Name" />
            </div>
            <div class="nineseas-field-label">@T("Name On Url") @Display(New.Controls_HelpPopup(Message: T("The Url address of the book (e.g. http://bellight.com/book/my-book ).<br/> Tip: this value is auto-generated as you type in the Name")))</div>
            <div class="nineseas-field-input">
                <input type="text" id="txtNameOnUrl" name="NameOnUrl" value="@Model.Book.NameOnUrl" />
            </div>
            <div class="nineseas-field-label">@T("Type") @Display(New.Controls_HelpPopup(Message: T("Select the type of book")))</div>
            <div class="nineseas-field-input">
                <label style="float: left; margin-right: 10px; font-size: small;">
                    <input type="radio" class="radioType" name="radioType" value="0" @(Model.Book.BookType == NineSeas.Models.BookTypeEnum.Text ? "checked=\"checked\"" : "") />
                    @T("Text")
                </label>
                <label style="float: left; font-size: small;">
                    <input type="radio" class="radioType" name="radioType" value="1" @(Model.Book.BookType == NineSeas.Models.BookTypeEnum.File ? "checked=\"checked\"" : "") />
                    @T("File")
                </label>
                <div style="clear: left"></div>
            </div>
            <div id="fileArea" @(Model.Book.BookType != NineSeas.Models.BookTypeEnum.File ? "style=display:none" : "")>
                <div class="nineseas-field-label">@T("File") @Display(New.Controls_HelpPopup(Message: T("Select a file to upload")))</div>
                <div class="nineseas-field-input">
                    <a href="@Model.Book.FileUrl" id="fileUrl">@fileName</a> <button id="buttonUploadFile">@T("Select a file to upload")</button>
                </div>
            </div>
            <div class="nineseas-field-label">@T("Tags") @Display(New.Controls_HelpPopup(Message: T("The list of keywords (a.k.a. Tags) that your book contains. These are used for search browsers to find your book.")))</div>
            <div class="nineseas-field-input">
                <input type="text" id="txtTags" name="Tags" value="@Model.Tags" />
                <span class="hint">@T("Separate multiple tags with commas")</span>
            </div>
            <div style="clear: both;"></div>
            <div class="nineseas-field-label">@T("Categories") @Display(New.Controls_HelpPopup(Message: T("Select the category for your book.")))</div>
            <div class="nineseas-field-input">
                @Display(New.Controls_CategorySelector(
                    SelectedCategories: Model.Book.Categories,
                    Categories: Model.Categories,
                    IsEdit: true
                ))
            </div>
            <div style="clear:both;"></div>
            <div class="nineseas-field-label">@T("Introduction")</div>
            <div class="nineseas-field-input">
                @Html.TextArea("txtIntroduction", (string)Model.Book.Introduction, 25, 80,
                         new Dictionary<string, object> {
		                    {"class", "html tinymce"},
                            {"style", "width:100%; height: 350px"}
	                     })
            </div>
            <div style="clear:both"></div>
        </div>
        <input type="hidden" id="imageStoragePath" value="@Model.Book.ImageStoragePath" />
        <input type="hidden" id="fileStoragePath" value="@Model.Book.FileStoragePath" />
    </div>
    <div id="nineseas-reader-footer"></div>
    <div id="throbber">
        <div class="curtain"></div>
        <div class="curtain-content">
            <div>
                <h1>@T("Processing ...")</h1>
                <p>
                    <img src="@Href("~/Modules/NineSeas/images/synchronizing.gif")" alt="" />
                </p>
            </div>
        </div>
    </div>
    @Display(New.Authoring_Book_SaveOptions())
</div>
@using (Script.Foot())
{
    <script type="text/javascript">
        //<![CDATA[
        $(function () {
            var updateEditorHeight = function() {
                var newHeight = $('#nineseas-reader-content').height() - 370;
                if (newHeight < 300) newHeight = 300;

                $('#txtIntroduction').height(newHeight + 10);

                if ($('#txtIntroduction_ifr').length > 0) {
                    $('#txtIntroduction_ifr').height(newHeight - 20);
                }
            };

            $('#nineseas-reader-content').bind("heightChanged", updateEditorHeight);

            $(".radioType").click(function () {
                var $this = $(this);

                if ($this.val() === "0") {
                    $("#fileArea").hide();
                } else {
                    $("#fileArea").show();
                }
            });

            var isNew = @Model.IsNew.ToString().ToLower();
            var chaptersUrl = "@Href(String.Format("~/Authoring/Books/Book/{0}/Chapters", Model.Book.Id ?? "[BOOK_ID]"))";
            var token = "@Html.AntiForgeryTokenValueOrchard()";

            var save = function ($data, onSaveSuccess) {
                // collect the form data
                var data = $.extend({
                    name: $("#txtName").val(),
                    nameOnUrl: $("#txtNameOnUrl").val(),
                    imageStoragePath: $('#imageStoragePath').val(),
                    bookType: $("input.radioType:checked").val(),
                    fileStoragePath: $('#fileStoragePath').val(),
                    Tags: $("#txtTags").val(),
                    //CategoryIds:
                    introduction: tinyMCE.activeEditor.getContent(),
                    '__RequestVerificationToken': token
                }, $data);

                var categoryIds = [];
                $(".categorySelector .selected-items .category").each(function () {
                    categoryIds.push($(this).attr("data-id"));
                });

                data.CategoryIds = categoryIds.join(",");

                $('#throbber').show();

                $.post("@Url.Action("Edit", "Books", new { id = Model.Book.Id})", data, function (result) {
                    $('#throbber').hide();
                    if (result.success) {
                        if (isNew && result.id) {
                            chaptersUrl = chaptersUrl.replace('[BOOK_ID]', "" + result.id);

                            var el = $('#nineseas-reader-footer')
                                .find("#chaptersButton")
                                .addClass('nineseas-button')
                                .removeClass('nineseas-button-disabled')
                                .bind('click', chaptersButton.onClick);
                        }

                        if (onSaveSuccess) onSaveSuccess();
                    } else if (result.message) {
                        $.alert(result.message);
                    } else {
                        $.alert('@T("An error has occurred while trying to save the data!")');
                    }
                }).always(function () {$('#throbber').hide();});
            };
            var listOfBookButton = {
                id: 'listOfBookButton',
                caption: '&lt; @T("your other books")',
                onClick: function () {
                    window.location.href = '@Href("~/Authoring")';
                }
            };
            var chaptersButton = {
                id: 'chaptersButton',
                caption: '@T("Table of Content") &gt;',
                isEnabled: !isNew,
                onClick: function () {
                    window.location.href = chaptersUrl;
                }
            };
            var saveButton = {
                id: 'saveButton',
                caption: '@T("Save")',
                onClick: function () {
                    $.showSaveOptions(function (saveOptions){
                        save(saveOptions.data, function () {
                            $.message('@T("The book was saved successfully.")', 1000, function () {
                                if (saveOptions.next == 'stay') return;
                                else if (saveOptions.next == 'toc') {
                                    window.location.href = chaptersUrl;
                                } else if (saveOptions.next == 'firstChapter') {
                                    window.location.href = "@Model.FirstChapterLink";
                                }
                            });
                        });
                    });
                }
            };

            $.commandBar('#nineseas-reader-footer', {
                left: [
                    listOfBookButton
                ],
                right: [saveButton, chaptersButton]
            });

            $('#imageArea').mediaUploadButton({
                'action': '@Url.Action("BookImage", "Upload")',
                'mediaName': 'BookImage',
                data: {
                    '__RequestVerificationToken': token
                },
                callback: function (result) {
                    if (result.success && result.filePath) {
                        $('#imageArea img').attr('src', result.publicUrl);
                        $('#imageStoragePath').val(result.filePath);
                    } else if (result.message) {
                        $.alert(result.message);
                    }
                }
            });

            $("#buttonUploadFile").mediaUploadButton({
                'action': '@Url.Action("BookFile", "Upload")',
                'mediaName': 'BookFile',
                data: {
                    '__RequestVerificationToken': token
                },
                callback: function (result) {
                    if (result.success && result.filePath) {
                        $('#fileUrl').html(result.publicUrl)
                            .attr("href", result.publicUrl);
                        $('#fileStoragePath').val(result.filePath);
                    } else if (result.message) {
                        $.alert(result.message);
                    }
                }
            });

            $.tagsAutocomplete.autocomplete(
                'txtTags',
                '@Url.Action("FetchSimilarTags", new { Controller = "Admin", Area = "Orchard.Tags" })', 1);
        });
        //]]>
    </script>
}